Page({
  data: {
    loading: true,
    searchKeyword: '',
    selectedCategory: 'all',
    categories: [
      { key: 'all', name: '全部资质', icon: '📋' },
      { key: 'business', name: '营业资质', icon: '🏢' },
      { key: 'technical', name: '技术资质', icon: '🔧' },
      { key: 'quality', name: '质量认证', icon: '✅' },
      { key: 'safety', name: '安全资质', icon: '🛡️' },
      { key: 'industry', name: '行业资质', icon: '🏭' }
    ],
    qualifications: [
      {
        id: 'qual_001',
        title: '营业执照',
        category: 'business',
        categoryName: '营业资质',
        certNumber: '91110000123456789X',
        issueDate: '2020-03-15',
        validDate: '长期有效',
        issuer: '北京市市场监督管理局',
        scope: '信息技术咨询服务、工程技术服务、计算机系统集成',
        status: 'valid',
        image: 'https://images.unsplash.com/photo-1554224155-6726b3ff858f?w=400',
        description: '公司合法经营的基础证明，涵盖信息技术、工程服务等多个业务领域。',
        level: 'A级',
        tags: ['基础资质', '必备证书', '合法经营']
      },
      {
        id: 'qual_002',
        title: '信息系统集成及服务资质',
        category: 'technical',
        categoryName: '技术资质',
        certNumber: 'XZ1110320200001',
        issueDate: '2023-06-20',
        validDate: '2026-06-19',
        issuer: '中国电子信息行业联合会',
        scope: '计算机信息系统集成、软件开发、技术服务',
        status: 'valid',
        image: 'https://images.unsplash.com/photo-1551434678-e076c223a692?w=400',
        description: '国家认可的信息系统集成服务资质，证明公司在信息化建设领域的专业能力。',
        level: '二级',
        tags: ['系统集成', '软件开发', '技术服务']
      },
      {
        id: 'qual_003',
        title: 'ISO9001质量管理体系认证',
        category: 'quality',
        categoryName: '质量认证',
        certNumber: 'ISO9001-2023-BJ-001',
        issueDate: '2023-09-15',
        validDate: '2026-09-14',
        issuer: '中国质量认证中心',
        scope: '信息技术服务、工程项目管理、技术咨询服务',
        status: 'valid',
        image: 'https://images.unsplash.com/photo-1450101499163-c8848c66ca85?w=400',
        description: '国际标准化组织质量管理体系认证，确保服务质量的持续改进和客户满意。',
        level: '国际标准',
        tags: ['质量管理', '国际认证', '持续改进']
      },
      {
        id: 'qual_004',
        title: '安全生产许可证',
        category: 'safety',
        categoryName: '安全资质',
        certNumber: 'AQ110-2023-001',
        issueDate: '2023-04-10',
        validDate: '2026-04-09',
        issuer: '北京市应急管理局',
        scope: '建筑工程、电力工程、通信工程安全施工',
        status: 'valid',
        image: 'https://images.unsplash.com/photo-1504384308090-c894fdcc538d?w=400',
        description: '安全生产作业许可证明，确保工程施工过程中的安全管理和风险控制。',
        level: 'B级',
        tags: ['安全施工', '风险控制', '合规作业']
      },
      {
        id: 'qual_005',
        title: '建筑业企业资质证书',
        category: 'industry',
        categoryName: '行业资质',
        certNumber: 'JZ110-2023-002',
        issueDate: '2023-07-25',
        validDate: '2028-07-24',
        issuer: '北京市住房和城乡建设委员会',
        scope: '建筑工程施工总承包、机电工程专业承包',
        status: 'valid',
        image: 'https://images.unsplash.com/photo-1541888946425-d81bb19240f5?w=400',
        description: '建筑行业专业资质证书，具备承接各类建筑和机电工程项目的合法资格。',
        level: '三级',
        tags: ['建筑工程', '机电工程', '总承包']
      },
      {
        id: 'qual_006',
        title: '高新技术企业证书',
        category: 'technical',
        categoryName: '技术资质',
        certNumber: 'GR202311000123',
        issueDate: '2023-11-30',
        validDate: '2026-11-29',
        issuer: '北京市科学技术委员会',
        scope: '软件和信息技术服务业',
        status: 'valid',
        image: 'https://images.unsplash.com/photo-1519389950473-47ba0277781c?w=400',
        description: '国家高新技术企业认定，体现公司在技术创新和研发能力方面的优势。',
        level: '国家级',
        tags: ['高新技术', '技术创新', '研发能力']
      },
      {
        id: 'qual_007',
        title: 'ISO27001信息安全管理体系认证',
        category: 'quality',
        categoryName: '质量认证',
        certNumber: 'ISO27001-2023-BJ-002',
        issueDate: '2023-12-08',
        validDate: '2026-12-07',
        issuer: '中国信息安全认证中心',
        scope: '信息技术服务、数据处理、网络安全服务',
        status: 'valid',
        image: 'https://images.unsplash.com/photo-1563013544-824ae1b704d3?w=400',
        description: '信息安全管理体系国际认证，确保客户数据和信息系统的安全保护。',
        level: '国际标准',
        tags: ['信息安全', '数据保护', '网络安全']
      },
      {
        id: 'qual_008',
        title: '计量器具型式批准证书',
        category: 'technical',
        categoryName: '技术资质',
        certNumber: 'CPA2023-F001',
        issueDate: '2023-05-18',
        validDate: '2028-05-17',
        issuer: '国家市场监督管理总局',
        scope: '电子测量仪器、环境监测设备校准检测',
        status: 'valid',
        image: 'https://images.unsplash.com/photo-1581092795360-fd1ca04f0952?w=400',
        description: '计量检测设备型式批准证书，具备专业计量校准和检测服务资格。',
        level: '国家级',
        tags: ['计量检测', '设备校准', '精密测量']
      }
    ],
    filteredQualifications: [],
    currentCategoryName: '全部资质',
    companyInfo: {
      name: '数智匠心科技有限公司',
      establishDate: '2020年3月',
      registeredCapital: '1000万元',
      legalRepresentative: '张总',
      businessScope: '信息技术咨询服务、工程技术服务、计算机系统集成、软件开发、技术推广服务',
      address: '贵阳市云岩区北京路天华大厦',
      phone: '400-888-8888',
      email: 'info@smartcraft.com'
    }
  },

  onLoad(options) {
    wx.setNavigationBarTitle({
      title: '企业资质'
    })
    
    // 如果有传入的分类参数，设置默认分类
    if (options.category) {
      const { categories } = this.data
      const currentCategory = categories.find(cat => cat.key === options.category)
      const currentCategoryName = currentCategory ? currentCategory.name : '全部资质'
      
      this.setData({
        selectedCategory: options.category,
        currentCategoryName: currentCategoryName
      })
    }
    
    this.initData()
  },

  // 初始化数据
  initData() {
    this.setData({
      loading: true
    })
    
    // 模拟加载延迟
    setTimeout(() => {
      this.filterQualifications()
      this.setData({
        loading: false
      })
    }, 800)
  },

  // 搜索资质
  onSearchInput(e) {
    const keyword = e.detail.value
    this.setData({
      searchKeyword: keyword
    })
    this.filterQualifications()
  },

  // 清除搜索
  clearSearch() {
    this.setData({
      searchKeyword: ''
    })
    this.filterQualifications()
  },

  // 选择分类
  onCategoryTap(e) {
    const { category } = e.currentTarget.dataset
    const { categories } = this.data
    
    // 找到当前分类的名称
    const currentCategory = categories.find(cat => cat.key === category)
    const currentCategoryName = currentCategory ? currentCategory.name : '全部资质'
    
    this.setData({
      selectedCategory: category,
      currentCategoryName: currentCategoryName
    })
    this.filterQualifications()
  },

  // 过滤资质
  filterQualifications() {
    const { qualifications, selectedCategory, searchKeyword } = this.data
    
    let filteredQualifications = qualifications
    
    // 按分类过滤
    if (selectedCategory !== 'all') {
      filteredQualifications = filteredQualifications.filter(item => item.category === selectedCategory)
    }
    
    // 按关键词过滤
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase()
      filteredQualifications = filteredQualifications.filter(item => 
        item.title.toLowerCase().includes(keyword) ||
        item.certNumber.toLowerCase().includes(keyword) ||
        item.issuer.toLowerCase().includes(keyword) ||
        item.scope.toLowerCase().includes(keyword) ||
        item.tags.some(tag => tag.toLowerCase().includes(keyword))
      )
    }
    
    console.log(`🔍 资质过滤结果: ${filteredQualifications.length}/${qualifications.length}`)
    
    this.setData({
      filteredQualifications
    })
  },

  // 查看资质详情
  viewQualificationDetail(e) {
    const { qualification } = e.currentTarget.dataset
    console.log('📖 查看资质详情:', qualification.title)
    
    wx.showModal({
      title: qualification.title,
      content: `证书编号：${qualification.certNumber}\n发证机关：${qualification.issuer}\n发证日期：${qualification.issueDate}\n有效期至：${qualification.validDate}\n\n业务范围：\n${qualification.scope}\n\n${qualification.description}`,
      showCancel: false,
      confirmText: '了解更多',
      success: () => {
        this.contactConsult(e)
      }
    })
  },

  // 预览资质证书
  previewCertificate(e) {
    const { qualification } = e.currentTarget.dataset
    console.log('🖼️ 预览资质证书:', qualification.title)
    
    if (qualification.image) {
      wx.previewImage({
        urls: [qualification.image],
        current: qualification.image
      })
    }
  },

  // 微信客服聊天回调
  onContactService(e) {
    console.log('💬 企业资质页面客服聊天回调:', e.detail)

    // 记录客服咨询事件
    try {
      wx.cloud.callFunction({
        name: 'businessManager',
        data: {
          action: 'logCustomerService',
          logData: {
            type: 'wechat_chat',
            source: 'qualification_page',
            path: e.detail.path || '',
            query: e.detail.query || '',
            timestamp: new Date()
          }
        }
      }).then(result => {
        console.log('客服咨询记录成功:', result)
      }).catch(error => {
        console.log('客服咨询记录失败:', error)
      })
    } catch (error) {
      console.log('记录客服咨询失败:', error)
    }

    // 显示提示信息
    wx.showToast({
      title: '客服聊天已打开',
      icon: 'success',
      duration: 2000
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.initData()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  }
})
